﻿using Audit.Core;
using Dapper_Core.BLL.Interface;
using Dapper_Core.Common;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using Dapper_Core.Table;
using ExpressionToWhere;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace Dapper_Core.BLL.Impl
{
    public class Sys_RoleBusiness : BaseRepository<Sys_Role>, ISys_RoleBusiness
    {
        public Sys_RoleBusiness()
        {

        }

        public Sys_RoleBusiness(TransactionContext transactionContext) : base(transactionContext)
        {

        }

        public bool IsExist(string roleCode, string roleId = "")
        {
            try
            {
                if (string.IsNullOrEmpty(roleCode)) return true;
                Expression<Func<Sys_Role, bool>> exp = role => role.RoleCode == roleCode;
                List<Sys_Role> list = base.GetList(exp, false).ToList();
                if (list != null && list.Count > 0 && list[0].RoleCode != roleId) return true;
                return false;
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "检查系统角色是否存在失败", "roleCode=" + roleCode + "，roleId=" + roleId, ex, "DapperCore");
                return false;
            }
        }

        public bool Add(Sys_Role role)
        {
            using (AuditScope scope = AuditScope.Create("Sys_Role:Add", () => role))
            {
                try
                {
                    scope.Comment("添加单个系统角色项");
                    scope.SetCustomField("Module", "Sys_Role");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Insert);
                    bool success = base.Add(role);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统角色添加失败", "role=" + JsonConvert.SerializeObject(role), ex, "DapperCore");
                    return false;
                }
            }
        }

        public bool UpdateNotNull(Sys_Role role)
        {
            Sys_Role old = base.Get(role.RoleCode);
            using (AuditScope scope = AuditScope.Create("Sys_Role:Edit", () => old))
            {
                try
                {
                    scope.Comment("编辑单个系统角色项");
                    scope.SetCustomField("Module", "Sys_Role");
                    scope.SetCustomField("Operator", SessionUtility.GetBasicUserInfo().PinyinCode);
                    scope.SetCustomField("Operation", Operation.Update);
                    old = role;
                    bool success = base.UpdateNotNull(role);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统角色修改失败", "menu=" + JsonConvert.SerializeObject(role), ex, "DapperCore");
                    return false;
                }
            }
        }

        public (List<Sys_Role> roles,int count) GetPageList(int pageIndex, int rowsPerPage, string search, string orderby)
        {
            try
            {
                if(pageIndex < 0 || rowsPerPage < 1)
                {
                    return (new List<Sys_Role>(), 0);
                }
                Expression<Func<Sys_Role, bool>> exp = role => role.IsDeleted == 0 && (role.RoleName.Contains(search) || role.RoleCode.Contains(search));
                List<Sys_Role> roles = base.GetPagelist(pageIndex + 1, rowsPerPage, exp, orderby).ToList();
                int count = base.GetListCount(exp);
                NlogUtility.WriteInfo(MethodBase.GetCurrentMethod().DeclaringType.FullName, "查询系统角色分页信息", "pageIndex=" + pageIndex + "，rowsPerPage=" + rowsPerPage + "，search=" + search + "，orderby=" + orderby, "DapperCore");
                return (roles, count);
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取角色分页信息失败", "pageIndex=" + pageIndex + "，rowsPerPage=" + rowsPerPage + "，search=" + search, ex, "DapperCore");
                return (new List<Sys_Role>(), 0);
            }
        }

        public List<Sys_ZTreeMenu> GetRolePermissionList(string userCode)
        {
            try
            {
                Expression<Func<Sys_User_Role, bool>> exp = userRole => userRole.UserCode == userCode;
                List<Sys_User_Role> userRoles = new Sys_User_RoleBusiness().GetList(exp).ToList();
                List<Sys_Role> roles = GetList(where: "").ToList();
                return GetZTreeMenus(roles, userRoles, "0");
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取“角色 - 用户有权访问的角色”之间的对应关系失败", "userCode=" + userCode, ex, "DapperCore");
                return new List<Sys_ZTreeMenu>();
            }
        }

        public bool Delete(string ids, string deleter)
        {
            using (AuditScope scope = AuditScope.Create("Sys_Role:Delete", () => ids))
            {
                try
                {
                    if (string.IsNullOrEmpty(ids)) return true;
                    List<string> idList = ids.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    if (idList.Count < 1) return true;
                    scope.Comment("软删除系统角色");
                    scope.SetCustomField("Module", "Sys_Role");
                    scope.SetCustomField("Operator", deleter);
                    scope.SetCustomField("Operation", Operation.Delete);
                    //定义时间变量，保证同一次删除数据的删除时间相等
                    DateTime dateTime = DateTime.Now;
                    Expression<Func<Sys_Role, bool>> exp = role => role.RoleCode.In(idList);
                    bool success = base.SoftDelete(exp, deleter, dateTime);
                    if (!success)
                    {
                        scope.Discard();
                    }
                    return success;
                }
                catch (Exception ex)
                {
                    scope.Discard();
                    NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "系统角色软删除失败", "ids=" + ids, ex, "DapperCore");
                    return false;
                }
            }
        }

        private List<Sys_ZTreeMenu> GetZTreeMenus(List<Sys_Role> roles, List<Sys_User_Role> userRoles, string parentCode)
        {
            List<Sys_ZTreeMenu> zTreeMenus = new List<Sys_ZTreeMenu>();
            Sys_ZTreeMenu zTreeMenu = null;
            List<Sys_Role> children = roles.Where(a => a.ParentCode == parentCode).OrderBy(a => a.RoleCode).ToList();
            foreach (Sys_Role role in children)
            {
                zTreeMenu = new Sys_ZTreeMenu();
                zTreeMenu.id = role.RoleCode;
                zTreeMenu.pId = role.ParentCode;
                zTreeMenu.name = role.RoleName;
                zTreeMenu.open = false;
                zTreeMenu.@checked = userRoles.Where(a => a.RoleCode == role.RoleCode).Count() > 0;
                zTreeMenu.menuId = role.RoleCode;
                zTreeMenu.children = GetZTreeMenus(roles, userRoles, role.RoleCode);
                if (zTreeMenu.children.Count < 1)
                {
                    zTreeMenu.iconSkin = "doc";
                    zTreeMenu.isParent = false;
                }
                else
                {
                    zTreeMenu.isParent = true;
                }
                zTreeMenus.Add(zTreeMenu);
            }
            return zTreeMenus.OrderBy(a => a.id).ToList();
        }
    }
}